import Api from '@/api'
import ls from '@/lib/ls'
import useConfigStore from '@/store/config'
import { showToast } from 'vant'
// 配置
const maps = {
    // 客户来源
    sourceList: {
        get: () => Api.Common.AppObjProcess.Do({ "functionName": "getCustomerSource", "contentData": "" }),
        set: function(resp) {
            this.sourceList = resp.result
        }
    },
    // 特殊要求列表
    specialList: {
        get: () => Api.Common.AppObjProcess.Do({ "functionName": "getSpecialRequire", "contentData": "" }),
        set: function(resp) {
            this.specialList = resp.result
        }
    },
    // 门店分区
    zoneList: {
        get: () => Api.Common.AppObjProcess.Do({ "functionName": "getRoomArea", "contentData": "" }),
        set: function(resp) {
            this.zoneList = resp.result
        }
    },
    // 房台信息
    roomList: {
        get: () => Api.Common.AppObjProcess.Do({ "functionName": "getRoomInfoNew", "contentData": "" }),
        set: function(resp) {
            console.log(resp);
            this.roomList = resp.result
        }
    },
    // 门店基础配置
    shopInfo:{
        get: () => Api.Common.AppObjProcess.Do({ "functionName": "GetBaseConfigInfo", "contentData": {orgCode:ls.get('ORG_CODE')} }),
        set: function(resp) {
            this.shopInfo = resp
        }
    },
    // 取消原因
    cancelList: {
        get: () => Api.Common.AppObjProcess.Do({ "functionName": "getCancelReason", "contentData": "" }),
        set: function(resp) {
            this.cancelList = resp.result
        }
    },
    // 商品分类列表
    categoryList: {
        get: () => Api.Common.AppObjProcess.Do({ "functionName": "getGoodsTypeOrg", "contentData": "" }),
        set: function(resp) {
            this.categoryList = resp.result
        }
    },
    // 商品信息列表
    goodsList: {
        // get: () => Api.Common.AppObjProcess.Do({ "functionName": "getGoodsInfo", "contentData": "" }),
        get: () =>Api.Common.AppObjProcess.Do({ "functionName": "getGoodsInfoTerminal", "contentData": {"terminalType":"1","currentTime":''} }),
        set: function(resp) {
            let obj = JSON.parse(JSON.stringify(resp))
            console.log(obj);
            
            try {
                if(this.shopInfo && resp.result){
                    resp.result.forEach(item => {
                        if (!item.attachment) {
                          item.attachment = this.shopInfo.WaiterMaterialPic;
                        }
                      });
                }
                // this.goodsList = JSON.parse(JSON.stringify(resp.result).replaceAll('\\"', '"').replaceAll('"[', "[").replaceAll(']"', "]"))
                this.goodsList = JSON.parse(JSON.stringify(resp.result))
                console.log(this.goodsList);
                
            } catch (error) {
                console.error(error)
            }
        }
    },
    // 赠送商品信息列表
    signCategoryList: {
        get: () => {
            const userCode = ls.get('USER_INFO').userCode
            return Api.Common.AppObjProcess.Do({ "functionName": "getSignGoodsList", "contentData": { userCode } })
        },
        set: function(resp) {
            try {
                this.signCategoryList = JSON.parse(JSON.stringify(resp.result).replaceAll('\\"', '"').replaceAll('"[', "[").replaceAll(']"', "]"))
                this.signCategoryList.forEach(item=>{
                    if(item.groupGoods){
                        item.groupGoods = filterGoods(item.groupGoods);
                    }
                })
                console.log(this.signCategoryList,'this.signCategoryListthis.signCategoryList');
            } catch (error) {
                console.error(error)
            }
        }
    },
}
function filterGoods(items) {
    const result = [];
    const uomMap = new Map();
  
    items.forEach(item => {
      const { goodsCode, uomCode } = item;
  
      // 检查 goodsCode 是否已存在于结果数组中
      if (!uomMap.has(goodsCode)) {
        // 如果不存在，将该元素添加到结果中，并初始化 uomCodeback
        result.push({ ...item, uomCodeback: [] });
        uomMap.set(goodsCode, result[result.length - 1]); // 记录在 uomMap 中
      } else {
        // 如果已存在，记录被过滤掉的 uomCode
        uomMap.get(goodsCode).uomCodeback.push(uomCode);
      }
    });
  
    // 在每个元素的 uomCodeback 中添加自己的 uomCode
    result.forEach(item => {
      item.uomCodeback.push(item.uomCode);
    });
  
    return result;
}
const goods = {
    // 商品分类列表
    categoryList: {
        get: () => Api.Common.AppObjProcess.Do({ "functionName": "getGoodsTypeOrg", "contentData": "" }),
        set: function(resp) {
            this.categoryList = resp.result
        }
    },
    // 商品信息列表
    goodsList: {
        // get: () => Api.Common.AppObjProcess.Do({ "functionName": "getGoodsInfo", "contentData": "" }),
        get: () =>Api.Common.AppObjProcess.Do({ "functionName": "getGoodsInfoTerminal", "contentData": {"terminalType":"1","currentTime":''} }),
        set: function(resp) {
            let obj = JSON.parse(JSON.stringify(resp))
            console.log(obj);
            
            try {
                if(this.shopInfo && resp.result){
                    resp.result.forEach(item => {
                        if (!item.attachment) {
                          item.attachment = this.shopInfo.WaiterMaterialPic;
                        }
                      });
                }
                // this.goodsList = JSON.parse(JSON.stringify(resp.result).replaceAll('\\"', '"').replaceAll('"[', "[").replaceAll(']"', "]"))
                this.goodsList = JSON.parse(JSON.stringify(resp.result))
                console.log(this.goodsList);
                
            } catch (error) {
                console.error(error)
            }
        }
    },
    // 赠送商品信息列表
    signCategoryList: {
        get: () => {
            const userCode = ls.get('USER_INFO').userCode
            return Api.Common.AppObjProcess.Do({ "functionName": "getSignGoodsList", "contentData": { userCode } })
        },
        set: function(resp) {
            try {
               
                
                this.signCategoryList = JSON.parse(JSON.stringify(resp.result).replaceAll('\\"', '"').replaceAll('"[', "[").replaceAll(']"', "]"))
                this.signCategoryList.forEach(item=>{
                    if(item.groupGoods){
                        item.groupGoods = filterGoods(item.groupGoods);
                    }
                })
            } catch (error) {
                console.error(error)
            }
        }
    },
}

export default {
    // // 修改值
    // setState(key,val){
    //     this[key] = val
    // },
    // 
    // // 更新所有配置
    // async UpdateAll(){
    //     const awaits = Object.values(maps)
    //     const resps = await Promise.all(awaits.map(c => c.get()))
    //     awaits.forEach((item,index)=>{
    //         item.set.bind(this)(resps[index])
    //     })
    // },
    connect(){
        // 连接成功后，将 isConnected 状态设置为 true
       const configStore = useConfigStore()
       configStore.isConnected = true
   },
   disconnect() {
       const configStore = useConfigStore()
       // 断开连接或退出登录时，将 isConnected 状态设置为 false
       configStore.isConnected = false
   },
    async UpdateAll() {
        let orgCode = ls.get('ORG_CODE')
        if(!orgCode){
            showToast('请重新登陆')
            return
        }
        const awaits = Object.values(maps)
        const promises = awaits.map(c => c.get())
        const results = await Promise.allSettled(promises)
        results.forEach((result, index) => {
            if (result.status === 'fulfilled') {
                const resp = result.value
                awaits[index].set.bind(this)(resp)
            } else {
                console.log('接口报错:', result.reason)
                // 可以选择继续执行其他接口请求，或者忽略错误并继续执行下面的代码
            }
        })
    },
    async UpdateGoods() {
        const awaits = Object.values(goods)
        const promises = awaits.map(c => c.get())
        const results = await Promise.allSettled(promises)
        results.forEach((result, index) => {
            if (result.status === 'fulfilled') {
                const resp = result.value
                awaits[index].set.bind(this)(resp)
            } else {
                console.log('接口报错:', result.reason)
                // 可以选择继续执行其他接口请求，或者忽略错误并继续执行下面的代码
            }
        })
    },
    // 更新配置
    async Update(...args) {
        const awaits = args.map((configName) => maps[configName])
        const resps = await Promise.all(awaits.map(c => c.get()))
        awaits.forEach((item, index) => {
            item.set.bind(this)(resps[index])
        })
    }
}